import type { RouterContext } from "@koa/router";

export type ControllerCallType = typeof controller;

export const controller = <T extends object, K extends keyof T & string>(
  c: T,
  m: K
) => {
  return async (ctx: RouterContext) => {
    const method = c[m];

    if (typeof method !== "function") {
      throw new Error(`"${m}" is not a method on controller`);
    }

    // 强制断言为函数类型（TS 无法自动从对象类型推导方法参数）
    const handler = method as unknown as (ctx: RouterContext) => Promise<any>;

    ctx.state.body = await handler.call(c, ctx);
  };
};
